<template>
  <upload-excel :on-success="handleSuccess" />
</template>

<script>
// 导入的excel数据接口
import { reqImportEmployee } from '@/api/employees'
export default {
  name: 'Import',
  //   判断页面是否跳转
  computed: {
    type() {
      return this.$route.query.type
    }
  },
  methods: {
    // header中, results中的数据是中文的, 但是提交给后台的要是英文的
    async handleSuccess({ header, results }) {
      console.log(header, results)
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      const arr = []
      results.forEach(item => {
        const obj = {}
        for (const k in item) {
          if (['timeOfEntry', 'correctionTime'].includes(userRelations[k])) {
            obj[userRelations[k]] = this.formatExcelDate(item[k], '-')
          } else {
            const enkey = userRelations[k]
            obj[enkey] = item[k]
          }
        }
        arr.push(obj)
      })
      //   console.log(arr)
      await reqImportEmployee(arr) // 调用导入接口
      this.$message.success('批量添加员工成功')
      this.$router.back()
      //   history.go()跳转
    //   history.forward()
    //   history.back()返回
    },
    // 转换Excel的日期格式
    formatExcelDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      // 毫秒
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }

  }

}
</script>

<style scoped lang="scss">

</style>
